package com.mzx.javase.thread.synchro;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 类描述：解决线程安全问题第三种方式： 使用Lock锁
 *
 * @ClassName MyListTest
 * @Description TODO
 * @Author 马子鑫
 * @Date 2022/8/5 10:15
 * @Version 1.0
 */
public class MyListTest {
    public static void main(String[] args) {
        MyList myList = new MyList();
        Runnable r1 = new Runnable() {
            @Override
            public void run() {
                myList.add("hello");
            }
        };
        Runnable r2 = new Runnable() {
            @Override
            public void run() {
                myList.add("world");
            }
        };
        Thread t1 = new Thread(r1, "线程1");
        Thread t2 = new Thread(r2, "线程2");
        t1.start();
        t2.start();

        try {
            t1.join();//让main线程等待t1线程合并后运行
            t2.join();//让main线程等待t2线程合并后运行
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        //遍历myList
        String[] strArray = myList.getStrArray();
        for (String s : strArray) {
            System.out.println(s);
        }

    }
}
class MyList{
    private String[] strArray= {"A","B","","",""};
    private int index = 2;
    private Lock lock = new ReentrantLock();

    public void add(String str) {

        lock.lock();
        try {
            strArray[index] = str;
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            index++;
            System.out.println(Thread.currentThread().getName() + "添加了：" + str);
        } finally {
            lock.unlock();
        }
        //此处容易产生线程安全问题，当一个线程赋值完成之后，由于没有上锁，没有完成下标移动；而另一个线程可能加入进来完成了赋值操作
//        try {
//            Thread.sleep(100);
//        } catch (InterruptedException e) {
//            throw new RuntimeException(e);
//        }
//        index++;
//        System.out.println(Thread.currentThread().getName() + "添加了：" + str);
        //解决思路：加锁，Lock锁



    }

    public String[] getStrArray() {
        return strArray;
    }
}
